import { ref } from 'vue'

export function useGenerateAggregateCode(baseUrl: string, params: { projectId: number; aggregateId: number; templateId: number }) {
  const code = ref<string | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function fetchCode() {
    loading.value = true
    error.value = null
    try {
      const url = `${baseUrl}/api/aggregate/generate-code?projectId=${params.projectId}&aggregateId=${params.aggregateId}&templateId=${params.templateId}`
      const res = await fetch(url)
      if (!res.ok) throw new Error('网络错误')
      const data = await res.json()
      code.value = data.generateCode
    } catch (e: any) {
      error.value = e.message || '未知错误'
    } finally {
      loading.value = false
    }
  }

  return { code, loading, error, fetchCode }
}
